<?php

namespace Admin\Controller;

class AdController extends AdminController {

    public function index() {

        $field = "*";
        $order = "sort";

        $jump_type[1] = '不跳转';
        $jump_type[2] = '单品详情';
        $jump_type[3] = '分类';
        $jump_type[4] = '头条';
        $jump_type[5] = '视频';
        $jump_type[6] = '链接';

        $M = M('Ad');

        $list = $this->lists($M, [], $order, $field);
        $this->assign('jump_type', $jump_type);
        $this->assign('_list', $list);
        $this->display();
    }

    public function add() {
        $id = I('id', 0, 'intval');
        if (IS_POST) {

            $data['title'] = I('title');
            $data['img_url'] = I("img_url");

            if (empty($data['title'])) {
                $this->error('请输入广告标题!');
                exit;
            }

            if (empty($data['img_url'])) {
                $this->error('请上传广告图!');
                exit;
            }
//            $ps = I('position_id', -1, 'intval');
//
//            if ($ps >= 1) {
//                $data['postion_id'] = $ps;
//            }

            $data['type'] = I("type", 1, 'intval');
            $to = I("to_id".$data['type']);


            if ($data['type'] != 1 && empty($to)) {
                $this->error('信息不完整!');
                exit;
            }

            $data['to'] = $to;

            $data['sort'] = I("sort", 0, 'intval');

            $data['start_time'] = I("start_time");
            $data['end_time'] = I("end_time");

            if ($data['end_time'] && $data['start_time']) {
                if ($data['end_time'] <= $data['start_time']) {
                    $this->error('开始时间不允许小于等于结束时间');
                    exit;
                }
            }


            if ($id == 0) {
                $res = M('Ad')->add($data);
            } else {
                $res = M('Ad')->where(array('ad_id' => $id))->save($data);
            }

            $this->success('操作成功', U('index', array('ps' => $ps)));

//            if ($res) {
//                $this->success('操作成功', U('index'));
//            } else {
//                $this->error('操作失败');
//            }
        } else {
            $data = M('Ad')->where(['ad_id' => $id])->find();

            $jump_type[1] = ['id' => 1, 'name' => '不跳转'];
            $jump_type[2] = ['id' => 2, 'name' => '单品详情'];
            $jump_type[3] = ['id' => 3, 'name' => '分类'];
            $jump_type[4] = ['id' => 4, 'name' => '头条'];
            $jump_type[5] = ['id' => 5, 'name' => '视频'];
            $jump_type[6] = ['id' => 6, 'name' => '链接'];

            $this->assign('jump_type', $jump_type);

            $this->assign('data', $data);
            $this->display();
        }
    }

    public function del() {
        $id = I('id', 0, 'intval');

        $res = M('Ad')->where(['ad_id' => $id])->delete();

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

}
